<template>
    <div class="f-sticky-wrapper" ref="wrapper" :style="{height}">
        <!-- ↓解决第二个bug -->
        <div class="f-sticky" :class="classes" :style="{left,width,top}">
            <slot></slot>
        </div>
    </div>
</template>

<script>
  export default {
    name: "FSticky"
    ,props:{
      distance:{
        type:Number
        ,default:0
      }
    }
    ,data(){
      return {
        sticky:false
        ,left:undefined
        ,width:undefined
        ,height:undefined
        ,top:undefined
      }
    }
    , mounted() {
      let {top} = this.$refs.wrapper.getBoundingClientRect(); //距离视口的位置 可能是负数
      this.windowScrollHandler = this._windowScrollHandler.bind(this, top);
      window.addEventListener('scroll', this.windowScrollHandler);
    }
    ,beforeDestroy() {
      window.removeEventListener('scroll',this.windowScrollHandler)
    }
    ,computed:{
      classes(){
        return {
          sticky:this.sticky
        }
      }
    }
    ,methods:{
      _windowScrollHandler(top) {
        if (window.scrollY > top - this.distance) {
          //一般页面可滚动时，高度已加载完毕 ↓解决第三个bug
          let {height, left, width} = this.$refs.wrapper.getBoundingClientRect();
          this.height = height + 'px';
          this.left = left + 'px';
          this.width = width + 'px';
          this.top = this.distance + 'px';
          this.sticky = true;
        } else {
          this.height = undefined;
          this.left = undefined;
          this.width = undefined;
          this.top = undefined;
          this.sticky = false;
        }
      }
    }

  }
</script>

<style lang="scss">
    .f-sticky{
        &.sticky{
            position:fixed;
        }
    }
</style>
